//
//  SISSHouseResourceEnrollViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/4/13.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSHouseResourceEnrollViewController.h"
#import "SISSPickerView.h"
#import "SISSTextView.h"
#import "SISSHouseResourceTagView.h"
#import "SISSEnrollHouseDetailViewController.h"
#import "SISSCooperationDetailViewController.h"
#import "SISSJsonRequestNetworkingManager+Registration.h"
#import "SISSMyEnrollHouseViewController.h"
#import "SISSNetworkingManager+Home.h"

#import "SISSRecommendPriceViewController.h"
#import "SISSHouseResourceCooperationViewController.h"
#import "SISSHouseRegistSuccessViewController.h"

@interface SISSHouseResourceEnrollViewController ()<UITextFieldDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet SISSBaseView *contentView;
@property (weak, nonatomic) IBOutlet UITextField *communityTextField;
@property (weak, nonatomic) IBOutlet UITextField *buildingTextField;
@property (weak, nonatomic) IBOutlet UITextField *landIdTextField;
@property (weak, nonatomic) IBOutlet UILabel *regionLabel;
@property (weak, nonatomic) IBOutlet UITextField *priceTextField;
@property (weak, nonatomic) IBOutlet UILabel *propertyLabel;
@property (weak, nonatomic) IBOutlet UILabel *houseTpyeLabel;
@property (weak, nonatomic) IBOutlet UITextField *areaTextField;
@property (weak, nonatomic) IBOutlet UITextField *insideAreaTextField;
@property (weak, nonatomic) IBOutlet UITextField *floorTextField;
@property (weak, nonatomic) IBOutlet UITextField *totalFloorsTextField;
@property (weak, nonatomic) IBOutlet UILabel *directionLabel;
@property (weak, nonatomic) IBOutlet UILabel *decorationLabel;
@property (weak, nonatomic) IBOutlet UILabel *buldingAgeLabel;
@property (weak, nonatomic) IBOutlet UILabel *houseResourceTagLabel;
@property (weak, nonatomic) IBOutlet UITextField *trustContractCodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *houseResourceCodeTextField;
@property (weak, nonatomic) IBOutlet SISSTextView *describeTextView;
@property (weak, nonatomic) IBOutlet UITextField *sellerNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *sellerPhoneNumTextField;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet UIButton *recommendPriceButton;

@property (weak, nonatomic) IBOutlet UITextField *allowAgentCoopTextField;
@property (weak, nonatomic) IBOutlet UITextField *releaseLimitTextField;
@property (weak, nonatomic) IBOutlet UITextField *ownerComissonPercentTextField;
@property (weak, nonatomic) IBOutlet UILabel *partnerCommissionPercentLabel;
@property (weak, nonatomic) IBOutlet SISSTextView *cooperationDescriptionTextView;
@property (weak, nonatomic) IBOutlet UIView *allowAgentView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *allowAgentHeightContraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewConstraint;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (assign, nonatomic) NSInteger allowAgent; // 1.
/** 房源合作范围 */
@property (assign, nonatomic) NSInteger cooperation_range; // 1.全行业2.公司。3门店

/** commissionPercentIndex */
@property (assign, nonatomic) NSInteger commissionPercentIndex;
/** 佣金比例 */
@property (assign, nonatomic) NSInteger commissionRate;


/** tagIndexArray */
@property (strong, nonatomic) NSMutableArray *tagIndexArray;
/** propertyIndex */
@property (assign, nonatomic) NSInteger propertyIndex;
/** areaFirstIndex */
@property (assign, nonatomic) NSInteger areaFirstIndex;
/** areaSecondIndex */
@property (assign, nonatomic) NSInteger areaSecondIndex;
/** houseTypeIndex */
@property (assign, nonatomic) NSInteger houseTypeIndex;
/** directionIndex */
@property (assign, nonatomic) NSInteger directionIndex;
/** decorationIndex */
@property (assign, nonatomic) NSInteger decorationIndex;
/** buildAgeIndex */
@property (assign, nonatomic) NSInteger buildAgeIndex;

///
@property (strong, nonatomic) SISSHouseDetailsInfoModel *houseDetailsInfo;

/** 记录是否点击了确定 */
@property (assign, nonatomic) BOOL isConfirm;

@end

@implementation SISSHouseResourceEnrollViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.recommendPriceButton.layer.cornerRadius = 4;
    self.recommendPriceButton.layer.masksToBounds = YES;
    self.recommendPriceButton.hidden = YES;
    
    self.title = @"房源登记";
    self.isConfirm = NO;
    self.bottomView.hidden = YES;
    self.bottomViewConstraint.constant = 1;
    self.allowAgent = 2;
    
    self.cooperationDescriptionTextView.placeholder = @"请输入合作说明";
    self.cooperationDescriptionTextView.layer.borderWidth = 1;
    self.cooperationDescriptionTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    // same font
    self.cooperationDescriptionTextView.font = [UIFont systemFontOfSize:15.f];
    
    self.commissionPercentIndex = 50;
    self.commissionRate = 50;

    // 添加左侧的关闭按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.communityTextField.delegate = self;
    self.priceTextField.delegate = self;
    self.areaTextField.delegate = self;
    self.insideAreaTextField.delegate = self;
    self.floorTextField.delegate = self;
    self.totalFloorsTextField.delegate = self;
    self.sellerNameTextField.delegate = self;
    self.sellerPhoneNumTextField.delegate = self;
    self.describeTextView.delegate = self;
    
    if (self.isModify) {
        
        self.allowAgentView.hidden = YES;
        self.allowAgentHeightContraint.constant = 1;
        
        self.propertyLabel.text = self.houseModel.propertyState;
        self.regionLabel.text = [NSString stringWithFormat:@"%@ %@",self.houseModel.region,self.houseModel.regionDetail];
        self.priceTextField.text = [NSString stringWithFormat:@"%0.f",[self.houseModel.price floatValue]];
        self.houseTpyeLabel.text = self.houseModel.houseType;
        self.areaTextField.text = self.houseModel.area.length ? self.houseModel.area : @" ";
        self.insideAreaTextField.text = self.houseModel.insideArea.length ? self.houseModel.insideArea : @"";
        self.floorTextField.text = self.houseModel.floor ? [NSString stringWithFormat:@"%zd",self.houseModel.floor] : @"";
        self.totalFloorsTextField.text = self.houseModel.totalFloor ? [NSString stringWithFormat:@"%zd",self.houseModel.totalFloor] : @"";
        self.directionLabel.text = self.houseModel.direction.length ? self.houseModel.direction : @"请选择朝向";
        self.decorationLabel.text = self.houseModel.decoration.length ? self.houseModel.decoration : @"请选择装修程度";
        self.buldingAgeLabel.text = self.houseModel.year.length > 0 && [self.houseModel.year integerValue] > 0 ? [NSString stringWithFormat:@"%@年",self.houseModel.year] : @"请选择建筑年代";
        NSString *tag;
        for (NSInteger i = 0; i < self.houseModel.listTag.count; i++) {
            
            SISSHouseResourceTagModel *tagModel = self.houseModel.listTag[i];
          tag = [NSString stringWithFormat:@"%@ ",tagModel.tag];
        }
        self.houseResourceTagLabel.text = tag.length ? tag : @"请选择房源标签";
//        self.trustContractCodeTextField.text = self.houseModel.contractNo;
//        self.houseResourceCodeTextField.text = self.houseModel.houseInfoNo;
        self.describeTextView.text = self.houseModel.otherdesc;
        self.sellerNameTextField.text = self.houseModel.name;
        self.sellerPhoneNumTextField.text = self.houseModel.phoneNumber;
//        self.
        
        [self.confirmButton setTitle:@"保存" forState:UIControlStateNormal];
        
        self.sellerNameTextField.userInteractionEnabled = NO;
        self.sellerPhoneNumTextField.userInteractionEnabled = NO;
        
        self.regionLabel.textColor = MAIN_TEXT_COLOR;
        self.propertyLabel.textColor = MAIN_TEXT_COLOR;
        self.houseTpyeLabel.textColor = MAIN_TEXT_COLOR;
        self.directionLabel.textColor = self.houseModel.direction.length ? MAIN_TEXT_COLOR : COLOR(0xC7C7CC);
        self.decorationLabel.textColor = self.houseModel.decoration.length ? MAIN_TEXT_COLOR : COLOR(0xC7C7CC);
        self.buldingAgeLabel.textColor = self.houseModel.year.length && [self.houseModel.year integerValue] > 0 ? MAIN_TEXT_COLOR : COLOR(0xC7C7CC);
        self.houseResourceTagLabel.textColor = self.houseModel.listTag && self.houseModel.listTag.count > 0 ? MAIN_TEXT_COLOR : COLOR(0xC7C7CC);
        
        self.communityTextField.textColor = SECONDARY_TEXT_COLOR;
        self.buildingTextField.textColor = SECONDARY_TEXT_COLOR;
        self.landIdTextField.textColor = SECONDARY_TEXT_COLOR;
        self.sellerPhoneNumTextField.textColor = SECONDARY_TEXT_COLOR;
        self.sellerNameTextField.textColor = SECONDARY_TEXT_COLOR;
    
    }
    /// 无论怎么进来都会赋值的
    self.communityTextField.text = self.houseModel.neighbourhood;
    self.buildingTextField.text = self.houseModel.bnum;
    self.landIdTextField.text = self.houseModel.dnum;
    
    
    //添加事件
    [self.communityTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}


//实现方法
- (void)textFieldDidChange:(UITextField *)textField {
    if (textField.text.length > 10) {
        //提示语
        [SISSTools showSVTitle:@"小区不能超过10个字" andTime:1 andColor:YES];
        //截取
        textField.text = [textField.text substringToIndex:10];
    }
}


#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    // 小区
//    if (textField == self.communityTextField) {
//        //在输入过程中 判断加上输入的字符 是否超过限定字数
//        NSString *str = [NSString stringWithFormat:@"%@%@",textField.text,string];
//        NSString *regex = @"[\u4e00-\u9fa5]+";
//        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
//        
//        if ([pred evaluateWithObject:textField.text] && str.length > 10) {
//            self.communityTextField.text = [str substringToIndex:10];
//            [SISSTools showSVTitle:@"小区不能超过10个字" andTime:1 andColor:YES];
//            return NO;
//        }
//    }
    // 售价
    if (textField == self.priceTextField) {
        //在输入过程中 判断加上输入的字符 是否超过限定字数
        NSString *str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if (str.length > 9) {
            [SISSTools showSVTitle:@"售价不能超过9位数字" andTime:1 andColor:YES];
            return NO;
        }
    }
    // 面积
    if (textField == self.areaTextField) {
        //在输入过程中 判断加上输入的字符 是否超过限定字数
        NSString *str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if (str.length > 9) {
            [SISSTools showSVTitle:@"面积不能超过9位数字" andTime:1 andColor:YES];
            return NO;
        }
    }
    
    // 楼层、总楼层
    if (textField == self.floorTextField || textField == self.totalFloorsTextField) {
        //在输入过程中 判断加上输入的字符 是否超过限定字数
        NSString *str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if (str.length > 3) {
            [SISSTools showSVTitle:@"楼层不能超过3位数字" andTime:1 andColor:YES];
            return NO;
        }
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    // 总楼层大于当前楼层
    if (self.totalFloorsTextField.text.length > 0 && self.floorTextField.text.length > 0 && (textField == self.totalFloorsTextField || textField == self.floorTextField) && [self.totalFloorsTextField.text integerValue] < [self.floorTextField.text integerValue] ) {
        [SISSTools showSVTitle:@"总楼层不能小于所在楼层" andTime:1 andColor:YES];
    }
    
    // 名字
    if (textField == self.sellerNameTextField && textField.text.length < 2) {
        
        [SISSTools showSVTitle:@"姓名不能少于2个字" andTime:1 andColor:YES];
    }

}


#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    //在输入过程中 判断加上输入的字符 是否超过限定字数
    NSString *str = [NSString stringWithFormat:@"%@%@",textView.text,text];
    if (str.length > 500) {
        [SISSTools showSVTitle:@"需求说明不能超过500个字" andTime:1 andColor:YES];
        return NO;
    }
    
    return YES;
}



/**
 返回关闭按钮的点击事件
 */
- (void)back {
    
    [self.view endEditing:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
//    [self.navigationController popViewControllerAnimated:YES];
//    return;
    if (self.isConfirm) { // 判断是否点击了确定
        [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        NSString *title = @"放弃";
        NSString *message = self.houseModel ? @"修改还未完成，您确定放弃吗？" : @"登记还未完成，您确定放弃吗？";
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        
        //改变title的大小和颜色
        NSMutableAttributedString *titleAtt = [[NSMutableAttributedString alloc] initWithString:title];
        [titleAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, title.length)];
        [titleAtt addAttribute:NSForegroundColorAttributeName value:COLOR(0x334A60) range:NSMakeRange(0, title.length)];
        [alertController setValue:titleAtt forKey:@"attributedTitle"];
        //改变message的大小和颜色
        NSMutableAttributedString *messageAtt = [[NSMutableAttributedString alloc] initWithString:message];
        [messageAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, message.length)];
        [messageAtt addAttribute:NSForegroundColorAttributeName value:COLOR(0x334A60) range:NSMakeRange(0, message.length)];
        [alertController setValue:messageAtt forKey:@"attributedMessage"];
        

        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"取消");
        }];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:confirmAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }

}


/**
 产权选择点击事件
 */
- (IBAction)propertyChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
   
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"产权";
    pickerView.titleArray = @[@"存在共有", @"不存在共有"];
    pickerView.isArea = NO;
    pickerView.firstIndex = self.propertyIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        weakself.propertyLabel.textColor = COLOR(0x334A60);
        weakself.propertyLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.propertyLabel.text = [NSString stringWithFormat:@"%@",firstTitle];
        weakself.propertyIndex = firstIndex;
        
//        [weakself houseTypeChooseTapAction:nil];
    };
}

/**
 区域选择点击事件
 */
- (IBAction)regionChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
    
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"区域";
    pickerView.isArea = YES;
    pickerView.firstIndex = self.areaFirstIndex;
    pickerView.secondIndex = self.areaSecondIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        weakself.regionLabel.textColor = COLOR(0x334A60);
        weakself.regionLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.regionLabel.text = [NSString stringWithFormat:@"%@ %@",firstTitle,secondTitle];
        weakself.areaFirstIndex = firstIndex;
        weakself.areaSecondIndex = secondIndex;
    };
}


/**
 推荐售价按钮点击事件
 */
- (IBAction)recommendPriceButtonClickAction:(UIButton *)sender {
    SISSRecommendPriceViewController *vc = [[SISSRecommendPriceViewController alloc] init];
    vc.communityName = self.houseModel.neighbourhood;
    vc.recommendPriceBlock = ^(NSString *avgPrice) {
        if (avgPrice.length > 0) {
            NSString *price = [NSString stringWithFormat:@"%.2f",([avgPrice floatValue] * [self.houseDetailsInfo.bsqar floatValue])*0.0001];
            self.priceTextField.text = price;
        }
    };
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 户型选择点击事件
 */
- (IBAction)houseTypeChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
    
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"户型";
    pickerView.titleArray = @[@"一房", @"二房", @"三房", @"四房", @"四房以上", @"复式", @"别墅", @"其他"];
    pickerView.isArea = NO;
    pickerView.firstIndex = self.houseTypeIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        weakself.houseTpyeLabel.textColor = COLOR(0x334A60);
        weakself.houseTpyeLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.houseTpyeLabel.text = [NSString stringWithFormat:@"%@",firstTitle];
        weakself.houseTypeIndex = firstIndex;
    };
}

/**
 朝向选择点击事件
 */
- (IBAction)directionChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
    
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"朝向";
    pickerView.titleArray = @[@"朝东", @"朝南", @"朝西", @"朝北", @"东南", @"东北", @"西北", @"西南"];
    pickerView.isArea = NO;
    pickerView.firstIndex = self.directionIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        weakself.directionLabel.textColor = COLOR(0x334A60);
        weakself.directionLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.directionLabel.text = [NSString stringWithFormat:@"%@",firstTitle];
        weakself.directionIndex = firstIndex;
        [weakself decorationChooseTapAction:nil];
        
    };
}

/**
 装修程度选择点击事件
 */
- (IBAction)decorationChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
    
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"装修程度";
    pickerView.titleArray = @[@"毛坯", @"普装", @"精装", @"豪装"];
    pickerView.isArea = NO;
    pickerView.firstIndex = self.decorationIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        weakself.decorationLabel.textColor = COLOR(0x334A60);
        weakself.decorationLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.decorationLabel.text = [NSString stringWithFormat:@"%@",firstTitle];
        weakself.decorationIndex = firstIndex;
        [weakself buldingAgeChooseTapAction:nil];
    };
}

/**
 建筑年代选择点击事件
 */
- (IBAction)buldingAgeChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
    
    //获取当前时间 （时间格式支持自定义）
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];//自定义时间格式
    NSString *currentDateStr = [formatter stringFromDate:[NSDate date]];
    //拆分年月成数组
    NSArray *dateArray = [currentDateStr componentsSeparatedByString:@"-"];
    NSMutableArray *yearArray;
    NSInteger currentYear = [[dateArray firstObject]integerValue];

    //初始化年数据源数组
    yearArray = [[NSMutableArray alloc]init];
    for (NSInteger i = currentYear ; i >= 1970 ; i--) {
        NSString *yearStr = [NSString stringWithFormat:@"%ld年",i];
        [yearArray addObject:yearStr];
    }
    
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"建筑年代";
    pickerView.titleArray = yearArray;
    pickerView.isArea = NO;
    pickerView.firstIndex = self.buildAgeIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        weakself.buldingAgeLabel.textColor = COLOR(0x334A60);
        weakself.buldingAgeLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.buldingAgeLabel.text = [NSString stringWithFormat:@"%@",firstTitle];
        weakself.buildAgeIndex = firstIndex;
        
        [weakself houseResourceTagChooseTapAction:nil];
    };
}

/**
 房源标签选择点击事件
 */
- (IBAction)houseResourceTagChooseTapAction:(id)sender {
    
    [self.view endEditing:YES];
    
    SISSHouseResourceTagView *pickerView = [[SISSHouseResourceTagView alloc] initWithFrame:self.view.bounds];
    
    pickerView.cacheIndexArray = self.tagIndexArray;
    __weak typeof(self) weakself = self;
    pickerView.getStringArrBlock = ^(NSMutableArray *stringArray, NSMutableArray *indexArray) {
        
        NSMutableString *mStr = [NSMutableString string];
        for (int i = 0; i < stringArray.count; i++) {
            [mStr appendFormat:@"%@ ",stringArray[i]];
        }
        weakself.houseResourceTagLabel.textColor = COLOR(0x334A60);
        weakself.houseResourceTagLabel.font = [UIFont boldSystemFontOfSize:13];
        weakself.houseResourceTagLabel.text = mStr.copy;
        
        weakself.tagIndexArray = indexArray;
    };
}

- (IBAction)allowAgentCoopTapAction:(id)sender {
    
    if (self.isModify) return;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor blackColor];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertController addAction:cancelAction];
    
    NSArray *limitArr = @[@"允许", @"不允许"];
    __weak typeof(self) weakSelf = self;
    for (NSInteger i = 0; i < limitArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:limitArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.allowAgent = i + 1;
            weakSelf.allowAgentCoopTextField.text = limitArr[i];
            weakSelf.allowAgentCoopTextField.font = [UIFont systemFontOfSize:16];
            if (i == 0) {
                self.bottomView.hidden = NO;
                self.bottomViewConstraint.constant = 434;
            } else {
                self.bottomView.hidden = YES;
                self.bottomViewConstraint.constant = 1;
            }
        }];
        
        [alertController addAction:action];
    }

    [self presentViewController:alertController animated:YES completion:nil];
}


/**
 选择发布合作范围点击事件
 */
- (IBAction)releaseLimitTapAction:(id)sender {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor blackColor];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertController addAction:cancelAction];
    
    NSArray *limitArr = @[@"全行业", @"公司", @"门店"];
    __weak typeof(self) weakSelf = self;
    for (NSInteger i = 0; i < limitArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:limitArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.cooperation_range = i + 1;
            weakSelf.releaseLimitTextField.text = limitArr[i];
            weakSelf.releaseLimitTextField.font = [UIFont systemFontOfSize:16];
        }];
        
        [alertController addAction:action];
    }

    [self presentViewController:alertController animated:YES completion:nil];
}

/**
 选择佣金百分比点击事件
 */
- (IBAction)partnerCommissionPercentClickAction:(id)sender {
    
    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
    pickerView.title = @"佣金百分比";
    NSMutableArray *titleArray = [NSMutableArray arrayWithCapacity:100];
    for (NSInteger i = 0; i < 100; i++) {
        
        [titleArray addObject:[NSString stringWithFormat:@"%zd",i]];
    }
    pickerView.titleArray = titleArray;
    pickerView.isArea = NO;
    pickerView.firstIndex = self.commissionPercentIndex;
    __weak typeof(self) weakself = self;
    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
        
        weakself.ownerComissonPercentTextField.textColor = COLOR(0x334A60);
        weakself.ownerComissonPercentTextField.font = [UIFont systemFontOfSize:16];
        weakself.ownerComissonPercentTextField.text = [NSString stringWithFormat:@"%@%@",firstTitle,@"%"];
        weakself.partnerCommissionPercentLabel.text =[NSString stringWithFormat:@"%zd%@",100 - [firstTitle integerValue],@"%"];
        weakself.commissionRate = [firstTitle integerValue];
        weakself.commissionPercentIndex = firstIndex;
        
    };
}



#pragma mark - 确定按钮点击事件
- (IBAction)confirmButtonClickAction:(UIButton *)sender {
    
    // 必填判读
//    if (self.trustContractCodeTextField.text.length == 0) {
//
//        [SISSTools showSVErrorTitle:@"请准确填写网签委托合同编码" andTime:2 andColor:YES];
//        return;
//    }
//    if (self.houseResourceCodeTextField.text.length == 0) {
//
//        [SISSTools showSVErrorTitle:@"请准确填写房源信息编码" andTime:2 andColor:YES];
//        return;
//    }
    if ([self.propertyLabel.text isEqualToString:@"请选择产权"]) {
        
        [SISSTools showSVErrorTitle:@"请选择产权" andTime:2 andColor:YES];
        return;
    }
    if ([self.regionLabel.text isEqualToString:@"请选择区域"]) {
        
        [SISSTools showSVErrorTitle:@"请选择区域" andTime:2 andColor:YES];
        return;
    }
    if (self.communityTextField.text.length == 0) {
        
        [SISSTools showSVErrorTitle:@"请准确填写小区" andTime:2 andColor:YES];
        if (self.communityTextField.text.length > 10) {
            [SISSTools showSVErrorTitle:@"最多输入10个字" andTime:2 andColor:YES];
        }
        return;
    }
    if (self.priceTextField.text.length == 0) {
        
        [SISSTools showSVErrorTitle:@"请准确填写售价" andTime:2 andColor:YES];
        return;
    }
    if ([self.houseTpyeLabel.text isEqualToString:@"请选择户型"]) {
        
        [SISSTools showSVErrorTitle:@"请选择户型" andTime:2 andColor:YES];
        return;
    }
    if (self.areaTextField.text.length == 0) {
        
        [SISSTools showSVErrorTitle:@"请准确填写建筑面积" andTime:2 andColor:YES];
        return;
    }
    if (self.insideAreaTextField.text.length == 0) {
        
        [SISSTools showSVErrorTitle:@"请准确填写套内面积" andTime:2 andColor:YES];
        return;
    }
    if (self.sellerNameTextField.text.length == 0) {
        
        [SISSTools showSVErrorTitle:@"请准确填写卖家姓名" andTime:2 andColor:YES];
        return;
    }
    if (self.sellerPhoneNumTextField.text.length == 0) {
        
        [SISSTools showSVErrorTitle:@"请准确填写卖家手机号" andTime:2 andColor:YES];
        return;
    }
    if (![NSString checkTelNumber:self.sellerPhoneNumTextField.text]) {
        [SISSTools showSVErrorTitle:@"请输入正确的手机号码" andTime:2 andColor:YES];
        return;
    }
       
   if (self.allowAgent == 1 && self.releaseLimitTextField.text.length == 0) {
       [SISSTools showSVErrorTitle:@"请选择合作发布范围" andTime:1.0 andColor:YES];
       return;
   };
   
   if (self.allowAgent == 1 && self.ownerComissonPercentTextField.text.length == 0) {
       [SISSTools showSVErrorTitle:@"请选择发布方佣金占比" andTime:1.0 andColor:YES];
       return;
   }
    
    SISSHouseResourceModel *houseModel = self.houseModel;
//    houseModel.contractNo = self.trustContractCodeTextField.text;
//    houseModel.houseInfoNo = self.houseResourceCodeTextField.text;
    houseModel.contractNo = @"";
    houseModel.propertyState = self.propertyLabel.text;
    NSArray *regionArr = [self.regionLabel.text componentsSeparatedByString:@" "];
    houseModel.region = regionArr[0];
    houseModel.regionDetail = regionArr.count > 1 ? regionArr[1] : @"";
    houseModel.neighbourhood = self.communityTextField.text;
    houseModel.price = self.priceTextField.text;
    houseModel.averagePrice = [NSString stringWithFormat:@"%f",[self.priceTextField.text floatValue] / [self.areaTextField.text floatValue]];
    houseModel.houseType = self.houseTpyeLabel.text;
    houseModel.area = self.areaTextField.text;
    houseModel.insideArea = self.insideAreaTextField.text;
    houseModel.floor = [self.floorTextField.text integerValue];
    houseModel.totalFloor = [self.totalFloorsTextField.text integerValue];
    houseModel.direction = [self.directionLabel.text isEqualToString:@"请选择朝向"] ? @"" : self.directionLabel.text;
    houseModel.decoration = [self.decorationLabel.text isEqualToString:@"请选择装修程度"] ? @"" : self.decorationLabel.text;
    houseModel.year = [self.buldingAgeLabel.text isEqualToString:@"请选择建筑年代"] ? @"" : (self.buldingAgeLabel.text.length > 0 ? [self.buldingAgeLabel.text substringToIndex:self.buldingAgeLabel.text.length - 1] : @"");
    NSString *houseTagStr = [self.houseResourceTagLabel.text isEqualToString:@"请选择房源标签"] ? @"" : self.houseResourceTagLabel.text;
    NSArray *tagArr = [houseTagStr componentsSeparatedByString:@" "];
    NSMutableArray *listTag = [NSMutableArray arrayWithCapacity:tagArr.count];
    NSInteger count = tagArr ? tagArr.count - 1 : 0;
    for (NSInteger i = 0; i < count; i++) {
        SISSHouseResourceTagModel *tagModel = [[SISSHouseResourceTagModel alloc] init];
        tagModel.tag = tagArr[i];
        tagModel.color = [self.tagIndexArray[i] integerValue] + 1;
        [listTag addObject:tagModel];
    }
    houseModel.listTag = listTag;
    houseModel.otherdesc = self.describeTextView.text;
    houseModel.name = self.sellerNameTextField.text;
    houseModel.phoneNumber = self.sellerPhoneNumTextField.text;
    houseModel.insertTime = [NSDate yyr_dateCurrentTimeString]; // 获取系统的当前时间
    
    [SISSPublicSingleton shared].isHud = NO;//
    
    if (self.isModify) {
        
        houseModel.asId = self.houseModel.asId;
        houseModel.ID = self.houseModel.ID;
        houseModel.asoId = self.houseModel.asoId;
        
        [self updateHouseWithHouseModel:houseModel];
    } else {
        [self enrollHouseWithHouseModel:houseModel];
    }
}

/**
 登记房源
 */
- (void)enrollHouseWithHouseModel:(SISSHouseResourceModel *)houseModel {
    
    
    [kJsonRequestNetworkingManager enrollHouseResourceWithHouseModel:houseModel successBlock:^(id responseObject) {
        
        NSLog(@"登记房源===>>>>%@",responseObject);
        
        if ([responseObject[@"code"] integerValue] == 200) { // 登记成功
            if (self.allowAgent == 1) {
        //        NSString *str = [NSString unicodeToISO88591:cooperation_desc];
                   NSString *cooperation_desc = self.cooperationDescriptionTextView.text;
                   NSDictionary *parameters = @{
                                                @"spId":[SISSUserAccount shared].spId,
                                                @"soId":[SISSUserAccount shared].soId,
                                                @"sobId":[SISSUserAccount shared].sobId,
                                                @"ahrId":responseObject[@"data"],
                                                @"cooperation_type":@(2),
                                                @"cooperation_range":@(self.cooperation_range),
                                                @"commission_rate":@(self.commissionRate),
                                                @"cooperation_desc":cooperation_desc
                                                };
                   [kNetworkManager releaseHouseCooperationWithparameters:parameters success:^(id responseObject) {
                       
                       NSLog(@"发布房源合作: %@",responseObject);
                       if ([responseObject[@"code"] integerValue] == 200) { // 发布成功
                           
                           [self enrollSuccessWithHouseModel:houseModel ahrId:responseObject[@"data"]];
                       }
                       
                   } failed:^(NSError *error) {
                       
                       NSLog(@"%@",error);
                   }];
            } else {
                [self enrollSuccessWithHouseModel:houseModel ahrId:responseObject[@"data"]];
            }
           
            
        } else { // 登记失败
            
            if (responseObject[@"message"]) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [SISSTools showSVTitle:responseObject[@"message"] andTime:1.0 andColor:YES];
                }];
            } else {
                [SISSTools showSVErrorTitle:@"登记失败" andTime:2 andColor:YES];
            }
        }
        
    } failed:^(NSError *error) {
        
        NSLog(@"客源登记error: %@",error);
    }];
}

- (void)enrollSuccessWithHouseModel:(SISSHouseResourceModel *)houseModel ahrId:(NSString *)ahrId {
    
    [SISSTools showSVTitle:@"登记成功！" andTime:1.0 andColor:YES];
    self.isConfirm = YES;
    if (self.isRegistration) {
        
        if (self.isCooperation) {
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[SISSHouseResourceCooperationViewController class]]) {
                    [self.navigationController popToViewController:controller animated:YES];
                }
            }
        } else {
//            SISSEnrollHouseDetailViewController *vc = [[SISSEnrollHouseDetailViewController alloc] init];
//            vc.title = @"房源详情";
//            vc.houseResourceModel = houseModel;
//            vc.isChange = self.isModify;
//            vc.isRegistration = self.isRegistration;
//            vc.deleteComplete = ^{
//
//                [self dismissViewControllerAnimated:YES completion:nil];
//            };
            SISSHouseRegistSuccessViewController *vc = [[SISSHouseRegistSuccessViewController alloc] init];
            vc.ahrId = ahrId;
            vc.isRegistration = self.isRegistration;
            vc.isCooperation = self.isCooperation;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } else { // 推荐房源进入
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:NSClassFromString(@"SISSRecommendHouseViewController")]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
//
//                [self.navigationController popViewControllerAnimated:YES];
//                [self dismissViewControllerAnimated:YES completion:nil];
    }
}

/**
 修改房源
 */
- (void)updateHouseWithHouseModel:(SISSHouseResourceModel *)houseModel {
    
    [kJsonRequestNetworkingManager updateHouseResourceWithHouseModel:houseModel successBlock:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 修改成功
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [SISSTools showSVTitle:@"修改成功！" andTime:1.0 andColor:YES];
            }];
            
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[SISSMyEnrollHouseViewController class]]) {
                    [self.navigationController popToViewController:controller animated:YES];
                }
            }
        }
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

#pragma mark - 数据请求
- (void)setLandId:(NSString *)landId {
    _landId = landId;
    if (landId.length > 0) {
        WeakSelf
        [kJsonRequestNetworkingManager requestHouseDetailsInfoWithLandId:landId successBlock:^(SISSHouseDetailsInfoModel *houseDetailsInfo) {
            
            weakSelf.houseDetailsInfo = houseDetailsInfo;
            if (houseDetailsInfo.huxing.length > 0) {
                weakSelf.houseTpyeLabel.textColor = COLOR(0x334A60);
                weakSelf.houseTpyeLabel.text = houseDetailsInfo.huxing;
            }
            if (houseDetailsInfo.bsqar.length > 0 && [houseDetailsInfo.bsqar floatValue] > 0) {
                weakSelf.areaTextField.text = houseDetailsInfo.bsqar;
            }
            if (houseDetailsInfo.inside.length > 0 && [houseDetailsInfo.inside floatValue] > 0) {
                weakSelf.insideAreaTextField.text = houseDetailsInfo.inside;
            }
            if (houseDetailsInfo.direct.length > 0) {
               weakSelf.directionLabel.text = houseDetailsInfo.direct;
            }
            
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
}

@end
